package tq.com.tqteacher.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.print.PrinterId;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import tq.com.systools.system.AlertDialogHelper;
import tq.com.tqcom.base.BaseFragment;
import tq.com.tqcom.base.BaseTitleRecycleFragment;
import tq.com.tqcom.net.INetCallback;
import tq.com.tqcom.net.TQNetClient;
import tq.com.tqcom.net.TQNetResult;
import tq.com.tqcom.recyclerAdapter.declear.IRecyclerSection;
import tq.com.tqcom.util.TQEventBus;
import tq.com.tqteacher.R;
import tq.com.tqteacher.activity.TQLookerDetailActivity;
import tq.com.tqteacher.adapt.TQHomePublishAdapter;
import tq.com.tqteacher.discuss.activity.TQDiscussMsgActivity;
import tq.com.tqteacher.inter.INewPulibshListener;
import tq.com.tqteacher.model.TQCommentOverInfoModel;
import tq.com.tqteacher.model.TQLogin;
import tq.com.tqteacher.model.TQLookerOverInfo;
import tq.com.tqteacher.model.TQNewPublish;
import tq.com.tqteacher.model.TQPublishItem;
import tq.com.tqteacher.model.TQPublishSection;
import tq.com.tqteacher.model.TQPublishType;
import tq.com.tqteacher.net.TQNetInterface;
import tq.com.tqteacher.view.TQHeaderPublish;

public class TQHomePublishFragment extends BaseFragment {
    private RecyclerView mRecyclerView;
    private TQHomePublishAdapter adapter;
    private INewPulibshListener mINewPulibshListener;
    private TQHeaderPublish mTQHeaderPublish;
    private SmartRefreshLayout mRefreshLayout;
    private int page = 1;

    private TQEventBus mTQEventBus = null;
    private TQPublishSection mPublishSection = null;
    private TQPublishItem mPublishItem = null;

    static public TQHomePublishFragment newInstance(INewPulibshListener pPulibshListener){
        TQHomePublishFragment lFragment = new TQHomePublishFragment();
        lFragment.mINewPulibshListener = pPulibshListener;
        return lFragment;
    }
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home_publish_layout, container, false);
        mTQHeaderPublish = view.findViewById(R.id.title);
        mTQHeaderPublish.setRightViewClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mINewPulibshListener != null){
                    mINewPulibshListener.newPublish();
                }
            }
        });
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRecyclerView = view.findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));

        if(adapter == null) {
            adapter = new TQHomePublishAdapter(getContext());
            adapter.setClickListener(mClickListener);
        }
        mRecyclerView.setAdapter(adapter);

        mRefreshLayout = view.findViewById(R.id.refresh);
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                loadData();
            }
        });
        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                loadData();
            }
        });
        mRefreshLayout.autoRefresh();

        if(mTQEventBus == null){
            mTQEventBus = new TQEventBus(mEventLisnter);
            mTQEventBus.register();
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        mTQEventBus.unregister();
    }

    private TQHomePublishAdapter.IClickListener mClickListener = new TQHomePublishAdapter.IClickListener() {
        @Override
        public void arrageLeaveMsg(TQPublishItem pItem) {
            Log.d(TAG, "arrageLeaveMsg: ");
        }

        @Override
        public void arragQuestion(TQPublishItem pItem) {
            Log.d(TAG, "arragQuestion: ");
        }

        @Override
        public void dataStatices(TQPublishItem pItem) {
            Log.d(TAG, "dataStatices: ");
        }

        @Override
        public void arrageContent(TQPublishItem pItem) {
            Log.d(TAG, "arrageContent: ");
        }

        @Override
        public void newLinker(TQPublishSection pItem) {
            mPublishSection = pItem;
            mINewPulibshListener.newListPublish(pItem);
        }

        @Override
        public void showViewer(TQPublishItem pItem) {
            Log.d(TAG, "showViewer: ");
            if(pItem == null) return;
            TQPublishType.setSharePublishItem(pItem.getNewPublish());
            TQPublishType.setTQOpenFrom(TQPublishType.TQOpenFrom.home);

            Intent intent = new Intent(getContext(), TQLookerDetailActivity.class);
            startActivity(intent);
        }

        @Override
        public void showLeverMsg(TQPublishItem pItem) {
            Log.d(TAG, "showLeverMsg: ");
            if(pItem == null) return;
            TQPublishType.setSharePublishItem(pItem.getNewPublish());
            TQPublishType.setTQOpenFrom(TQPublishType.TQOpenFrom.home);

            TQPublishType.showLeaveMsg(TQHomePublishFragment.this.getActivity());
        }

        @Override
        public void showDetail(TQPublishItem pItem) {
            Log.d(TAG, "showDetail: ");
            if(pItem == null) return;

            mPublishItem = pItem;
            TQPublishType.setSharePublishItem(pItem.getNewPublish());
            TQPublishType.setTQOpenFrom(TQPublishType.TQOpenFrom.home);
            TQPublishType.showResult(TQHomePublishFragment.this.getActivity());
        }
    };

    private void loadData(){
        int cls = TQLogin.getCurrent().getUserInfo().getClzid();
        int subject = TQLogin.getCurrent().getUserInfo().getSubject();

        TQNetInterface.getPublishLink(cls, subject, page,new INetCallback() {
            @Override
            public void result(TQNetResult pNetResult) {
                boolean isRefresh = false;
                if(mRefreshLayout.getState() == RefreshState.Loading){
                    mRefreshLayout.finishLoadMore();
                }else{
//                    isRefresh = true;
                    mRefreshLayout.finishRefresh();
                }
                if(page == 1){
                    isRefresh = true;
                }

                if(!pNetResult.isSuccess() || pNetResult.getData() == null){
                    AlertDialogHelper.show(TQHomePublishFragment.this.getContext(), pNetResult.getErrMsg());
                    return;
                }

                ArrayList<TQNewPublish> lNewPublishes = new ArrayList<>();
                JSONArray material = pNetResult.getData().optJSONArray("material");
                if(material == null) return;

                for (int i = 0; i < material.length(); i++){
                    try {
                        JSONObject lObject = material.getJSONObject(i);
                        JSONObject lPublish = lObject.optJSONObject("material");
                        int type = lPublish.optInt("category");

                        if(!TQPublishType.isValidType(type)){
                            continue;
                        }

                        TQNewPublish lPublish1 = TQPublishType.getNewPublishByType(type);
                        lPublish1.fromJson(lPublish);

                        TQCommentOverInfoModel lOverInfoModel = new TQCommentOverInfoModel(lObject);
                        lPublish1.setCommentOverInfoModel(lOverInfoModel);

                        TQLookerOverInfo lLookerOverInfo = new TQLookerOverInfo(lObject);
                        lPublish1.setLookerOverInfo(lLookerOverInfo);

                        lNewPublishes.add(lPublish1);
                    }catch (JSONException pE){
                        pE.printStackTrace();
                    }
                }

                if(lNewPublishes.size() > 0){
                    mkGroup(lNewPublishes, !isRefresh);
                }else{
                    //no more
                    return;
                }

                if(adapter.getItemCount() < 10){
                    page++;
                    loadData();
                }

            }
        });

    }

    private void mkGroup(ArrayList<TQNewPublish> pNewPublishes, boolean append){
        ArrayList<IRecyclerSection> datas = new ArrayList<>();

        TQPublishSection lPublishSection = null;
        for (TQNewPublish pulish:
             pNewPublishes) {
            TQPublishItem lItem = new TQPublishItem();
            lItem.setNewPublish(pulish);

            if(lPublishSection == null || pulish.isHeader()){
                lPublishSection = new TQPublishSection();
                lPublishSection.setHeaderItem(lItem);

                datas.add(lPublishSection);
            }else{
                lPublishSection.addItem(lItem);
            }

//            if(!pulish.hasChild()){
//                lPublishSection = null;
//            }
        }

        if(datas.size() > 0){
            if(!append){
                adapter.clear();
            }
            adapter.addSections(datas);
        }
    }

    private TQEventBus.IEventLisnter mEventLisnter = new TQEventBus.IEventLisnter() {
        @Override
        public void onEvnet(TQEventBus.TQEventMessage msg) {
            if(TQPublishType.getTQOpenFrom() != TQPublishType.TQOpenFrom.home){
                return;
            }

            if(msg.getOperator() == TQEventBus.TQEventMessage.Opertor.add
                    && TQPublishType.getSharePublishItem() != null && msg.getInfo() == null){
                TQNewPublish lPublish = TQPublishType.getSharePublishItem();
                TQPublishItem lItem = new TQPublishItem(lPublish);

                if(mPublishSection != null){
                    adapter.insertItem(mPublishSection, lItem);
                }else{
                    TQPublishSection lSection = new TQPublishSection();
                    lSection.setHeaderItem(lItem);
                    adapter.insertSection(0, lSection);

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mRecyclerView.scrollToPosition(0);
                        }
                    });
                }

                mPublishSection = null;
            }else if(msg.getOperator() == TQEventBus.TQEventMessage.Opertor.modify){
                if(mPublishItem != null){
                    adapter.update(mPublishItem);
                }

            }
        }
    };

    public void cancelLinkNewPublish(){
        mPublishSection = null;
    }
}
